"use client";
import { GameListRep, GameRequest } from "@/api/home";
import { userInfoApi } from "@/api/login";
import {
    UserInfoRep,
    UserVipInfo,
    Wallet,
    cleanBounsApi,
    getUserMoneyApi,
    getUserTransferApi,
} from "@/api/user";
import {
    BalanceContent,
    BonusContent,
    FreeContent,
    ReplayContent,
} from "@/components/ModalPopup/WalletDescribeModal";
import TipsModal, { ModalProps } from "@/components/TipsModal";
import useGame from "@/hooks/useGame";
import { Link, useRouter } from "@/i18n/routing";
import { useWalletStore } from "@/stores/useWalletStore";
import { WalletEnum } from "@/types";
import { copyText, percentage } from "@/utils/methods";
import { Badge, Button, Mask, ProgressBar, Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useEffect, useMemo, useRef, useState } from "react";

type Props = {
    userInfo: UserInfoRep;
    userMoney: Wallet;
    userVip: UserVipInfo;
};
const VipCard = (props: { userVip: UserVipInfo }) => {
    const { userVip } = props;
    const t = useTranslations("ProfilePage");
    const router = useRouter();

    // Vip 图标
    // const vipIconElement = vipImages.map((item, index) => {
    //     if (item.leve === userVip?.vip_level) {
    //         return (
    //             <Fragment key={index}>
    //                 <Image src={item.src} className="block" alt={"vip"} height={110} width={100} />
    //                 <span className={"icon-level"} style={{ color: item.color }}>
    //                     {item.leve}
    //                 </span>
    //             </Fragment>
    //         );
    //     }
    // });

    if (!userVip) return null;
    return (
        <div className={"vip-card"}>
            {/* <div className={"vip-card__icon"}>{vipIconElement}</div> */}
            <div className={"vip-card-process"}>
                {/*<div className={"process-top"}>{userVip.vip_exp}xp</div>*/}

                <div className="relative mr-[.1rem] flex-1 px-[.3rem]">
                    <ProgressBar
                        percent={percentage(userVip?.vip_exp, userVip?.vip_score_exp)}
                        style={{
                            "--fill-color": "#11de68",
                            "--track-color": "#2b363f",
                            "--track-width": ".12rem",
                        }}
                    />
                    <div className={"process-bottom text-[#e581ff]"}>
                        <span className="bg-[#0abd71]">VIP{userVip?.vip_level}</span>
                        <div className={"process-bottom-desc"}>
                            {userVip.vip_exp}/{userVip.vip_score_exp}
                        </div>
                        <span className="bg-[#eac61f]">
                            VIP
                            {userVip.vip_next_level}
                        </span>
                    </div>
                </div>
                <div className="vip-card-text" onClick={() => router.push("/vip")}>
                    <span className="underline">CLUBE VIP</span>
                    <i className="iconfont icon-xiangzuo1 block rotate-[180deg]"></i>
                </div>
            </div>
        </div>
    );
};

const WalletCard = (props: { userMoney: Wallet }) => {
    const { userMoney } = props;
    const t = useTranslations("ProfilePage");
    const tcdoe = useTranslations();

    const tipsRef = useRef<ModalProps>(null);
    const [tipsStatus, setTipsStatus] = useState<keyof typeof WalletEnum>("Bonus");

    const modalHandler = (key: keyof typeof WalletEnum) => {
        setTipsStatus(key);
        tipsRef.current?.onOpen();
    };

    // 未完成游戏
    const gameModelRef = useRef<ModalProps>(null);
    const game = useRef<(GameListRep & { mode: GameRequest["mode"] }) | null>(null);

    // 彩金、免费币、重玩币提现到钱包操作
    const handleAcquire = async (wallet_type: number, transfer: boolean) => {
        if (!transfer) return;

        // 先判断是否有未完成的游戏
        const { data }: any = await userInfoApi();

        // 如果有未完成游戏 彩金游戏-2、免费游戏-3、重玩游戏-4
        if (wallet_type === 2 && data.play_list && data.play_list.length > 0) {
            game.current = data.play_list[0];
            game.current!.mode = 1;
            gameModelRef.current?.onOpen();
            return;
        }

        if (wallet_type === 3 && data.free_game_list && data.free_game_list.length > 0) {
            game.current = data.free_game_list[0];
            gameModelRef.current?.onOpen();
            game.current!.mode = 2;
            return;
        }

        if (wallet_type === 4 && data.lose_game_list && data.lose_game_list.length > 0) {
            game.current = data.lose_game_list[0];
            game.current!.mode = 3;
            gameModelRef.current?.onOpen();
            return;
        }

        getUserTransferApi({ wallet_type })
            .then((res) => {
                if (res.code === 200) {
                    Toast.show(tcdoe("code.200"));
                    setTimeout(() => {
                        tipsRef.current?.onClose();
                    }, 1000);
                }
            })
            .catch((error) => {
                Toast.show(tcdoe(`code.${error.data.code}`));
            });
    };

    const { getGameUrl } = useGame();
    const goGame = () => {
        const current = game.current;
        getGameUrl(current!, { id: current?.id + "", mode: game.current?.mode! });
        tipsRef.current?.onClose();
        gameModelRef.current?.onClose();
    };

    const walletCfg = useMemo(() => {
        return [
            {
                title: t("balance"),
                icon: "icon-qianbao3",
                onClick: () => modalHandler(WalletEnum.Balance),
                value: userMoney.score || "0.0",
                key: "balance",
                dot: userMoney.is_point_transfer ? Badge.dot : null,
            },
            {
                title: t("bonus"),
                icon: "icon-meiyuanzhanghuyue",
                onClick: () => modalHandler(WalletEnum.Bonus),
                value: userMoney.point || "0.0",
                key: "bonus",
                dot: userMoney.is_point_transfer ? Badge.dot : null,
            },
            {
                title: t("free"),
                icon: "icon-Free-Tag",
                onClick: () => modalHandler(WalletEnum.Free),
                value: userMoney.free_score || "0.0",
                key: "free",
                iconStyle: { fontSize: ".22rem" },
                dot:
                    userMoney.is_free_transfer &&
                    userMoney.free_score >= (userMoney?.free_transfer_min || 0)
                        ? Badge.dot
                        : null,
            },
            {
                title: t("replay"),
                icon: "icon-meiyuan2",
                onClick: () => modalHandler(WalletEnum.Replay),
                value: userMoney.lose_score || "0.0",
                key: "replay",
                dot:
                    userMoney.is_lose_transfer &&
                    userMoney.lose_score >= (userMoney?.lose_transfer_min || 0)
                        ? Badge.dot
                        : null,
            },
        ];
    }, [userMoney]);

    return (
        <>
            <TipsModal
                className="walletModal"
                ref={tipsRef}
                title={
                    <div className={"flex items-center text-[#11de68]"}>
                        <i
                            className={"iconfont icon-liwuhuodong mr-[0.0694rem] text-[0.2778rem]"}
                        ></i>
                        {t("modalTitle")}
                    </div>
                }
            >
                {/*现金*/}
                {tipsStatus === WalletEnum.Balance ? <BalanceContent wallet={userMoney} /> : null}
                {/*  彩金*/}
                {tipsStatus === WalletEnum.Bonus ? (
                    <BonusContent wallet={userMoney} handleAcquire={handleAcquire} />
                ) : null}
                {/* 免费币 */}
                {tipsStatus === WalletEnum.Free ? (
                    <FreeContent wallet={userMoney} handleAcquire={handleAcquire} />
                ) : null}
                {/*  重玩币 */}
                {tipsStatus === WalletEnum.Replay ? (
                    <ReplayContent wallet={userMoney} handleAcquire={handleAcquire} />
                ) : null}
            </TipsModal>
            {/*   提现拦截 */}
            <TipsModal title={"Tips"} ref={gameModelRef}>
                <p className={"text-left text-[0.12rem] font-medium text-[#666]"}>
                    Existem jogos de bônus pendentes que não podem iniciar a retirada.
                </p>

                <div className={"mt-[0.0694rem] flex justify-center"}>
                    <Button
                        color={"primary"}
                        className={"mx-auto"}
                        style={{
                            "--background-color": "var(--primary-color)",
                            "--border-color": "var(--primary-color)",
                        }}
                        onClick={goGame}
                    >
                        para jogos
                    </Button>
                </div>
            </TipsModal>
            <div className="coin">
                <div className={"coin_right_wallet"}>
                    {walletCfg.map((item, index) => {
                        return (
                            <div
                                key={item.key}
                                className={"wallet_right_content"}
                                onClick={item.onClick}
                            >
                                <Badge
                                    content={item.dot}
                                    style={{
                                        right: "4px",
                                        top: "50%",
                                        width: "6px",
                                        height: "6px",
                                        minWidth: "6px",
                                    }}
                                >
                                    <div className="wallet-right-icon">
                                        <span
                                            className={clsx("coin_left__icon iconfont", item.icon)}
                                            style={{ ...(item.iconStyle || {}) }}
                                        ></span>
                                    </div>
                                </Badge>
                                <section>
                                    <div className={"wallet_header"}>
                                        {item.title}
                                        <div className="wallet-question">?</div>
                                    </div>
                                    <div className="num">
                                        <span className="uppercase">R$</span>
                                        <span>{item.value}</span>
                                    </div>
                                </section>
                            </div>
                        );
                    })}
                </div>
            </div>
        </>
    );
};
const NoBounsWarn = ({ visible, onClose, onConfirm }: any) => {
    const doClose = () => {
        if (typeof onClose === "function") onClose();
    };
    const doConfirm = () => {
        if (typeof onConfirm === "function") onConfirm();
    };

    return (
        <Mask visible={visible} onMaskClick={doClose}>
            <div className="absolute left-[50%] top-[40%] w-[80%] translate-x-[-50%]">
                <div className="relative rounded-[.1rem] bg-[#1f2830] px-[.15rem] pb-[.15rem] pt-[0px]">
                    <div className="h-[.5rem] text-center">
                        <img
                            src="/warn_top.png"
                            alt=""
                            className="relative -top-[.3rem] inline-block w-[.9rem]"
                        />
                    </div>
                    <div className="text-center text-[.12rem]">
                        A demanda atual de fluxo de retirada de bônus é excessiva，Se esvaziar o
                        bônus e retirar a demanda de água corrente？
                    </div>
                    <div className="mt-[.2rem] flex items-center justify-between px-[.1rem]">
                        <button
                            onClick={doConfirm}
                            className="mr-[.1rem] h-[.35rem] flex-1 rounded-[60px] bg-[#11de68] text-[.14rem] font-bold text-[#12171a]"
                        >
                            A certeza
                        </button>
                        <button
                            onClick={doClose}
                            className="h-[.35rem] flex-1 rounded-[60px] bg-[#ebc71f] text-[.14rem] font-bold text-[#12171a]"
                        >
                            Cancelar
                        </button>
                    </div>
                    <i
                        className="iconfont icon-guanbi absolute right-[.1rem] top-[.1rem]"
                        onClick={doClose}
                    ></i>
                </div>
            </div>
        </Mask>
    );
};
export const ProfileHeader = (props: Props) => {
    const { userInfo, userVip } = props;
    const t = useTranslations("ProfilePage");
    const tc = useTranslations();

    const { wallet, setWallet } = useWalletStore((state) => ({
        wallet: state.wallet,
        setWallet: state.setWallet,
    }));
    const router = useRouter();
    const [isShowNoBounsWarn, setIsShowNoBounsWarn] = useState(false);
    const [isShowed, setIsShowed] = useState(false);
    useEffect(() => {
        const curMul = wallet.target_point_rollover / ((wallet?.score || 0) + (wallet.point || 0));
        const config = wallet.no_bonus_config;
        if (curMul >= (config || 0) && !isShowed) {
            setIsShowNoBounsWarn(true);
            setIsShowed(true);
        }
    }, [wallet]);

    const handler = () => {
        if (!!wallet.score) {
            router.push("/deposit?target=2");
        } else {
            Toast.show("no money");
        }
    };

    const doConfirm = async () => {
        Toast.show({
            icon: "loading",
            maskClickable: false,
        });
        setIsShowNoBounsWarn(false);
        const res = await cleanBounsApi(1);
        if (res?.code && [6001, 6002].includes(res?.data?.code)) {
            const str = t(`bouns${res?.data?.code}`);
            Toast.show({
                content: str,
                icon: "fail",
            });
        }
        Toast.show({
            content: t("success"),
            icon: "success",
        });
        const walletRes = await getUserMoneyApi();
        setWallet(walletRes?.data);
    };

    const doCopyUsreId = () => {
        copyText(userInfo?.user_phone || "");
        Toast.show({ icon: "success", content: tc("SummaryPage.copySuc"), maskClickable: false });
    };

    return (
        <>
            <div className={"userContent"}>
                <div className={"userInfo"}>
                    <div>
                        <div className={"bgImg"}>
                            <Image
                                src={"/img/avatar.png"}
                                className={"h-[100%] w-[100%]"}
                                alt={"avatar"}
                                width={120}
                                height={120}
                            />
                        </div>
                        <div>
                            <span className="font-bold">{t("Conta")}</span>
                            <div className="flex items-center">
                                <span className="phone text-[#7b939a]">
                                    {userInfo?.user_phone || ""}
                                </span>
                                <i
                                    className="iconfont icon-fuzhi1 text-[#7b939a]"
                                    onClick={doCopyUsreId}
                                ></i>
                            </div>
                        </div>
                    </div>

                    {/* <Link
                        className="goto iconfont icon-xiangzuo1 text-[#7b939a]"
                        href={`/changePassword`}
                    ></Link> */}
                </div>
                {/*vipcard*/}
                <VipCard userVip={userVip} />

                <WalletCard userMoney={wallet} />
            </div>

            <div className="link">
                <Link href={"/deposit"} className={"btn"}>
                    <i className="iconfont icon-meiyuanzhanghuyue mr-[.1rem]"></i>
                    <span>{t("Depósito")}</span>
                </Link>
                <p className={"btn"} onClick={handler}>
                    <i className="iconfont icon-zhuishou-meiyuan-shi mr-[.1rem]"></i>
                    <span>{t("Sacar")}</span>
                </p>
            </div>
            <NoBounsWarn
                visible={isShowNoBounsWarn} // 控制是否显示遮罩层，true 显示，false 不显示
                onClose={() => setIsShowNoBounsWarn(false)}
                onConfirm={doConfirm}
            ></NoBounsWarn>
        </>
    );
};
